package com.mengshu.token;

import com.mengshu.token.api.LoginUser;
import com.mengshu.token.handler.PermissionFailureHandler;
import com.mengshu.token.handler.PermissionFinishedHandler;
import com.mengshu.token.helper.LoginHelper;
import com.mengshu.token.interceptor.PermissionHandlerInterceptor;
import com.mengshu.token.interceptor.PermissionWebMvcConfigurer;
import com.mengshu.token.properties.TokenProperties;
import com.mengshu.token.storage.RedisConfig;
import com.mengshu.token.storage.RedisUserStorage;
import com.mengshu.token.storage.UserStorage;
import com.mengshu.token.utils.TokenConfigUtils;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Optional;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(TokenProperties.class)
@ImportAutoConfiguration(RedisConfig.class)
@ConditionalOnProperty(prefix = TokenProperties.PREFIX, name = "enable", havingValue = "true", matchIfMissing = true)
public class TokenAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public PermissionWebMvcConfigurer permissionWebMvcConfigurer(TokenConfigUtils tokenConfigUtils, PermissionHandlerInterceptor permissionHandlerInterceptor) {
        return new PermissionWebMvcConfigurer(tokenConfigUtils, permissionHandlerInterceptor);
    }

    @Bean
    @ConditionalOnMissingBean
    public PermissionHandlerInterceptor permissionRequestBodyAdviceAdapter(TokenConfigUtils tokenConfigUtils, LoginHelper loginHelper, Optional<PermissionFailureHandler> permissionFailureHandler, Optional<PermissionFinishedHandler> permissionFinishedHandler) {
        return new PermissionHandlerInterceptor(tokenConfigUtils, loginHelper, permissionFailureHandler.orElse(null), permissionFinishedHandler.orElse(null));
    }

    @Bean
    @ConditionalOnMissingBean
    public UserStorage userStorage(RedisTemplate<String, LoginUser> redisTemplate) {
        return new RedisUserStorage(redisTemplate);
    }

    @Bean
    @ConditionalOnMissingBean
    public LoginHelper loginHelper(TokenConfigUtils tokenConfigUtils, UserStorage userStorage) {
        return new LoginHelper(tokenConfigUtils, userStorage);
    }

    @Bean
    @ConditionalOnMissingBean
    public TokenConfigUtils tokenUtils(TokenProperties tokenProperties) {
        return new TokenConfigUtils(tokenProperties);
    }
}
